package com.wyzz.hr.bo.impl;

import com.wyzz.hr.bo.IEmpBenefitPlanBo;
import com.wyzz.hr.bo.IEmpSalaryAcctitemsBo;
import com.wyzz.hr.dao.IEmpBenefitDao;
import com.wyzz.hr.pojo.Empbenefit;
import com.wyzz.hr.pojo.Empbenefitplan;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Empsalaryacctitems;
import com.wyzz.hr.pojo.Empsalarydatadef;
import com.wyzz.hr.pojo.Empsalarypay;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.StringUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.*;
import org.springframework.util.ObjectUtils;

public class EmpBenefitPlanBoImpl implements IEmpBenefitPlanBo {

	public EmpBenefitPlanBoImpl() {
	}

	public List findEbp(DetachedCriteria dc, Pager page, String searchOrExport) {
		List ebpList = null;
		if (page == null || "export".equals(searchOrExport)) {
			ebpList = empBenefitDao.findByCriteria(dc);
		} else {
			page.splitPage(dc);
			ebpList = empBenefitDao.findByCriteria(dc, page.getPageSize(), page
					.getCurrentPage());
		}
		if (ebpList != null && ebpList.size() > 0) {
			Empbenefitplan ebp;
			for (Iterator i$ = ebpList.iterator(); i$.hasNext(); ebp
					.decryEMPPlan(ebp))
				ebp = (Empbenefitplan) i$.next();

		}
		return ebpList;
	}

	public void calcEbp(List ebpList) {
		if (ebpList == null || ebpList.size() == 0)
			return;
		IEmpSalaryAcctitemsBo itemsBo = (IEmpSalaryAcctitemsBo) SpringBeanFactory
				.getBean("empsalaryacctitemsBo");
		Map acctItemsMap = itemsBo.getItemsByEmpbenefitplan(ebpList);
		for (Iterator i$ = ebpList.iterator(); i$.hasNext();) {
			Empbenefitplan ebp = (Empbenefitplan) i$.next();
			ebp = calcEbpForPage(ebp, (List) acctItemsMap.get(ebp
					.getEbpEsavId().getId()));
		}

	}

	public void processDataForExport(List ebpList, List dataDefList) {
		IEmpSalaryAcctitemsBo itemsBo = (IEmpSalaryAcctitemsBo) SpringBeanFactory
				.getBean("empsalaryacctitemsBo");
		Map acctItemsMap = itemsBo.getItemsByEmpbenefitplan(ebpList);
		List acctItems = null;
		if (ebpList != null) {
			Empbenefitplan ebp;
			for (Iterator i$ = ebpList.iterator(); i$.hasNext(); generateOutputList(
					ebp, dataDefList, acctItems)) {
				ebp = (Empbenefitplan) i$.next();
				acctItems = (List) acctItemsMap.get(ebp.getEbpEsavId().getId());
			}

		}
	}

	private void generateOutputList(Empbenefitplan ebp,
			List<Empsalarydatadef> dataDefList,
			List<Empsalaryacctitems> acctItems) {
		Map outPutList = new HashMap();
		Class ebpClass = Empbenefitplan.class;
		Method ebpMethod = null;
		BigDecimal itemValue = null;
		boolean find = false;
		for (Empsalarydatadef datadef : dataDefList) {
			find = false;
			for (Empsalaryacctitems item : acctItems) {
				if (datadef.getEsddId().equals(item.getEsaiEsdd().getEsddId())) {
					try {
						ebpMethod = ebpClass.getMethod("getEbpColumn"
								+ item.getEsaiDataSeq(), new Class[0]);
						itemValue = (BigDecimal) ebpMethod.invoke(ebp,
								new Object[0]);
						outPutList.put(datadef.getEsddId(), itemValue);
						find = true;
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				}
			}
			if (!find) {
				outPutList.put(datadef.getEsddId(), new BigDecimal(0.0D));
			}
		}
		ebp.setOutPutList(outPutList);
	}

	public Empbenefitplan calcEbpForPage(Empbenefitplan ebp, List items) {
		List sumList = new ArrayList();
		for (int i = 0; i <= 20; i++)
			sumList.add(new BigDecimal(0));

		Class ebpClass = ebp.getClass();
		Method ebpMethod = null;
		BigDecimal temp = null;
		Empsalaryacctitems esai = null;
		int i = 0;
		for (int j = items.size(); i < j; i++) {
			esai = (Empsalaryacctitems) items.get(i);
			try {
				ebpMethod = ebpClass.getMethod((new StringBuilder()).append(
						"getEbpColumn").append(esai.getEsaiDataSeq())
						.toString(), new Class[0]);
				temp = (BigDecimal) ebpMethod.invoke(ebp, new Object[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (temp != null)
				sumList.set(esai.getEsaiEsdd().getEsddDataType().intValue(),
						((BigDecimal) sumList.get(esai.getEsaiEsdd()
								.getEsddDataType().intValue())).add(temp));
		}

		ebp.setShowColumn15((BigDecimal) sumList.get(15));
		ebp.setShowColumn16((BigDecimal) sumList.get(16));
		return ebp;
	}

	public List searchEbpByEmpandMonth(String empId[], String yearMonth,
			String yearmonthArr[]) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.add(Restrictions.eq(Empbenefitplan.PROP_EBP_STATUS,
				new Integer(1)));
		detachedCriteria.add(Restrictions.in("ebpEmpno.id", empId));
		detachedCriteria.add(Restrictions.eq(Empbenefitplan.PROP_EBP_YEARMONTH,
				yearMonth));
		detachedCriteria.add(Restrictions.in(
				Empbenefitplan.PROP_EBP_BELONG_YEARMONTH, yearmonthArr));
		List ebpList = empBenefitDao.findByCriteria(detachedCriteria);
		return ebpList;
	}

	public Map findEbpYMs(String yearMonths[], Integer status, boolean isSum,
			String empIds[]) {
		List ebpList = findEbpBatch(yearMonths, null, status, empIds);
		if (ebpList == null || ebpList.size() == 0)
			return null;
		else
			return generateEbpMap(ebpList, false, isSum);
	}

	public Map findEbpBelongYMs(String belongYearMonths[], Integer status,
			boolean isSum, String empIds[]) {
		List ebpList = findEbpBatch(null, belongYearMonths, status, empIds);
		if (ebpList == null || ebpList.size() == 0)
			return null;
		else
			return generateEbpMap(ebpList, false, isSum);
	}

	private Map generateEbpMap(List ebpList, boolean isYearMonth, boolean isSum) {
		if (ebpList == null || ebpList.size() == 0)
			return null;
		Map ebpMap = new HashMap();
		String key = null;
		for (Iterator i$ = ebpList.iterator(); i$.hasNext();) {
			Empbenefitplan ebp = (Empbenefitplan) i$.next();
			if (isYearMonth)
				key = (new StringBuilder()).append(ebp.getEbpYearMonth())
						.append(" ").append(
								ebp.getEbpEmpno().getEmpDistinctNo()).append(
								" ").append(ebp.getEbpEmpno().getEmpName())
						.toString();
			else
				key = (new StringBuilder()).append(ebp.getEbpBelongYearmonth())
						.append(" ").append(
								ebp.getEbpEmpno().getEmpDistinctNo()).append(
								" ").append(ebp.getEbpEmpno().getEmpName())
						.toString();
			if (!isSum) {
				ebpMap.put(key, ebp);
			} else {
				Empbenefitplan ebpSum = (Empbenefitplan) ebpMap.get(key);
				if (ebpSum == null)
					try {
						ebpSum = (Empbenefitplan) ebp.clone();
					} catch (CloneNotSupportedException e) {
						e.printStackTrace();
					}
				else
					ebpSum = sumEbpYMs(ebpSum, ebp);
				ebpMap.put(key, ebpSum);
			}
		}

		return ebpMap;
	}

	private List findEbpBatch(String yearMonths[], String belongYearMonths[],
			Integer status, String empIds[]) {
		if (empIds == null)
			return null;
		DetachedCriteria dc = DetachedCriteria.forClass(Empbenefitplan.class);
		if (status != null)
			dc.add(Restrictions.eq(Empbenefitplan.PROP_EBP_STATUS, status));
		dc.add(Restrictions.in("ebpEmpno.id", empIds));
		if (yearMonths != null) {
			dc.add(Restrictions.in(Empbenefitplan.PROP_EBP_YEARMONTH,
					yearMonths));
			dc.addOrder(Order.asc(Empbenefitplan.PROP_EBP_YEARMONTH));
		} else {
			dc.add(Restrictions.in(Empbenefitplan.PROP_EBP_BELONG_YEARMONTH,
					belongYearMonths));
			dc.addOrder(Order.asc(Empbenefitplan.PROP_EBP_BELONG_YEARMONTH));
		}
		List ebpList = empBenefitDao.findByCriteria(dc);
		if (ebpList == null || ebpList.size() == 0)
			return null;
		Empbenefitplan ebp;
		for (Iterator i$ = ebpList.iterator(); i$.hasNext(); ebp
				.decryEMPPlan(ebp))
			ebp = (Empbenefitplan) i$.next();

		IEmpSalaryAcctitemsBo esaiBo = (IEmpSalaryAcctitemsBo) SpringBeanFactory
				.getBean("empsalaryacctitemsBo");
		if (!esaiBo.setAcctItemsEbp((Empbenefitplan[]) ebpList
				.toArray(new Empbenefitplan[ebpList.size()])))
			return null;
		else
			return ebpList;
	}

	private Empbenefitplan sumEbpYMs(Empbenefitplan ebpSum, Empbenefitplan ebp) {
		if (ebp == null)
			return ebpSum;
		if (ebpSum == null)
			return null;
		try {
			for (int i = 1; i <= 48; i++) {
				Object ebpValue = PropertyUtils.getProperty(ebp,
						(new StringBuilder()).append("ebpColumn").append(i)
								.toString());
				Object ebpSumValue = PropertyUtils.getProperty(ebpSum,
						(new StringBuilder()).append("ebpColumn").append(i)
								.toString());
				if (ebpValue != null)
					if (ebpSumValue == null) {
						PropertyUtils.setProperty(ebpSum, (new StringBuilder())
								.append("ebpColumn").append(i).toString(),
								ebpValue);
					} else {
						BigDecimal value = ((BigDecimal) ebpValue)
								.add((BigDecimal) ebpSumValue);
						PropertyUtils.setProperty(ebpSum, (new StringBuilder())
								.append("ebpColumn").append(i).toString(),
								value.setScale(2));
					}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return ebpSum;
	}

	public Empbenefitplan deductEbpYMs(Empbenefitplan ebpSum, Empbenefitplan ebp) {
		if (ebp == null) {
			return ebpSum;
		} else {
			ebp = reverseEbpYMs(ebp);
			return sumEbpYMs(ebpSum, ebp);
		}
	}

	private Empbenefitplan reverseEbpYMs(Empbenefitplan ebp) {
		if (ebp == null)
			return null;
		try {
			for (int i = 1; i <= 48; i++) {
				Object ebpValue = PropertyUtils.getProperty(ebp,
						(new StringBuilder()).append("ebpColumn").append(i)
								.toString());
				if (ebpValue != null) {
					BigDecimal newValue = ((BigDecimal) ebpValue)
							.multiply(new BigDecimal("-1.00"));
					PropertyUtils.setProperty(ebp, (new StringBuilder())
							.append("ebpColumn").append(i).toString(), newValue
							.setScale(2));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return ebp;
	}

	public List searchEbpById(String ebpId[]) {
		if (ebpId == null)
			return null;
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.createAlias(Empbenefitplan.PROP_EBP_EMP_NO,
				"ebpEmpno", 1);
		detachedCriteria.createAlias("ebpEmpno.config", "config", 1);
		detachedCriteria.add(Restrictions.in("ebpId", ebpId));
		List ebpList = empBenefitDao.findByCriteria(detachedCriteria);
		if (ebpList.isEmpty())
			return null;
		else
			return ebpList;
	}

	public Empbenefitplan searchEmpbenefitByEmpMonth(String empId,
			String yearMonth) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefit.class);
		detachedCriteria.add(Restrictions.eq("employee.id", empId));
		String nextYearMonth = getNextMonth(yearMonth);
		org.hibernate.criterion.LogicalExpression exp1 = Restrictions.and(
				Restrictions.isNull("ebfEndMonth"), Restrictions.le(
						"ebfStartMonth", nextYearMonth));
		org.hibernate.criterion.LogicalExpression exp21 = Restrictions.or(
				Restrictions.or(Restrictions.between("ebfStartMonth",
						yearMonth, nextYearMonth), Restrictions.between(
						"ebfEndMonth", yearMonth, nextYearMonth)), Restrictions
						.and(Restrictions.lt("ebfStartMonth", yearMonth),
								Restrictions.gt("ebfEndMonth", nextYearMonth)));
		detachedCriteria.add(Restrictions.or(exp1, Restrictions.and(
				Restrictions.isNotNull("ebfEndMonth"), exp21)));
		List benefitList = empBenefitDao.findByCriteria(detachedCriteria);
		Empbenefitplan plan = null;
		Iterator i$ = benefitList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Empbenefit empBenefit = (Empbenefit) i$.next();
			if (isDateInPeriod(yearMonth, empBenefit.getEbfStartMonth(),
					empBenefit.getEbfEndMonth()))
				plan = new Empbenefitplan(empBenefit);
		} while (true);
		return plan;
	}

	private String getNextMonth(String current) {
		Integer year = Integer.valueOf(current.substring(0, 4));
		Integer month = Integer.valueOf(current.substring(4, 6));
		Integer nextYear = Integer.valueOf(0);
		Integer nextMonth = Integer.valueOf(0);
		if (month.intValue() == 12) {
			nextMonth = Integer.valueOf(1);
			nextYear = Integer.valueOf(year.intValue() + 1);
		} else {
			nextMonth = Integer.valueOf(month.intValue() + 1);
			nextYear = year;
		}
		String nextYearMonth = (new StringBuilder()).append(nextYear).append(
				nextMonth.intValue() >= 10 ? (new StringBuilder()).append(
						nextMonth).append("").toString()
						: (new StringBuilder()).append("0").append(nextMonth)
								.toString()).toString();
		return nextYearMonth;
	}

	private boolean isDateInPeriod(String current, String dateStart,
			String dateEnd) {
		if (current.compareTo(dateStart) < 0)
			return false;
		return !StringUtils.isNotEmpty(dateEnd)
				|| current.compareTo(dateEnd) <= 0;
	}

	public List searchEbpByEmpMonths(String empId, String yearMonths[]) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.createAlias(Empbenefitplan.PROP_EBP_EMP_NO,
				"ebpEmpno", 1);
		detachedCriteria.add(Restrictions.eq("ebpEmpno.id", empId));
		detachedCriteria.add(Restrictions.in(Empbenefitplan.PROP_EBP_YEARMONTH,
				yearMonths));
		detachedCriteria.add(Restrictions.eq(Empbenefitplan.PROP_EBP_STATUS,
				new Integer(0)));
		List ebpList = empBenefitDao.findByCriteria(detachedCriteria);
		return ebpList;
	}

	public Empbenefitplan searchInitEbpByEmpMonth(String empId, String yearMonth) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.createAlias(Empbenefitplan.PROP_EBP_EMP_NO,
				"ebpEmpno", 1);
		detachedCriteria.add(Restrictions.eq((new StringBuilder()).append(
				"ebpEmpno.").append(Employee.PROP_ID).toString(), empId));
		detachedCriteria.add(Restrictions.eq(Empbenefitplan.PROP_EBP_YEARMONTH,
				yearMonth));
		detachedCriteria.add(Restrictions.eq(Empbenefitplan.PROP_EBP_STATUS,
				new Integer(0)));
		List ebpList = empBenefitDao.findByCriteria(detachedCriteria);
		if (ebpList != null && ebpList.size() > 0) {
			Empbenefitplan initEbp = (Empbenefitplan) ebpList.get(0);
			initEbp.decryEMPPlan(initEbp);
			return initEbp;
		} else {
			return null;
		}
	}

	public String batchSaveEbp(List ebpList) {
		empBenefitDao.saveOrupdate(ebpList);
		Set empNameSet = new TreeSet();
		Set yearMonthSet = new TreeSet();
		Empbenefitplan plan;
		for (Iterator i$ = ebpList.iterator(); i$.hasNext(); yearMonthSet
				.add(plan.getEbpBelongYearmonth())) {
			plan = (Empbenefitplan) i$.next();
			empNameSet.add(plan.getEbpEmpno().getEmpName());
		}

		String concatStr = StringUtil.addConcatStr("", "\u3001", empNameSet
				.toArray(new Object[empNameSet.size()]));
		concatStr = (new StringBuilder()).append(concatStr).append("(").append(
				StringUtil.addConcatStr("", "\u3001", yearMonthSet
						.toArray(new Object[yearMonthSet.size()]))).append(")")
				.toString();
		return concatStr;
	}

	public boolean setAddEbpSum(String yearMonth, Empsalarypay payArray[]) {
		if (ObjectUtils.isEmpty(payArray))
			return false;
		Map ebpMap = getSumEbpsOfMonth(yearMonth, payArray);
		Empsalarypay arr$[] = payArray;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			Empsalarypay pay = arr$[i$];
			Empbenefitplan additionalPlan = (Empbenefitplan) ebpMap
					.get((new StringBuilder())
							.append(pay.getEspEmpno().getId()).append("")
							.append(yearMonth).toString());
			pay.setAddBenefitPlan(additionalPlan);
			if (additionalPlan == null)
				pay.setEspBenefitPlans(Integer.valueOf(0));
			else
				pay.setEspBenefitPlans(additionalPlan.getEmpMonthCount());
		}

		return true;
	}

	public Map getSumEbpsOfMonth(String yearMonth, Empsalarypay payArray[]) {
		String empIds[] = new String[payArray.length];
		for (int i = 0; i < payArray.length; i++)
			empIds[i] = payArray[i].getEspEmpno().getId();

		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.createAlias(Empbenefitplan.PROP_EBP_EMP_NO,
				"ebpEmpno", 1);
		if (empIds != null && empIds.length > 0)
			detachedCriteria.add(Restrictions.in("ebpEmpno.id", empIds));
		detachedCriteria.add(Restrictions.eq(Empbenefitplan.PROP_EBP_YEARMONTH,
				yearMonth));
		detachedCriteria.add(Restrictions.eq(Empbenefitplan.PROP_EBP_STATUS,
				new Integer(1)));
		List ebpList = empBenefitDao.findByCriteria(detachedCriteria);
		IEmpSalaryAcctitemsBo esaiBo = (IEmpSalaryAcctitemsBo) SpringBeanFactory
				.getBean("empsalaryacctitemsBo");
		esaiBo.setAcctItemsEbp((Empbenefitplan[]) ebpList
				.toArray(new Empbenefitplan[ebpList.size()]));
		Map payMap = new HashMap();
		Empsalarypay arr$[] = payArray;
		int len$ = arr$.length;
		for (int i$ = 0; i$ < len$; i$++) {
			Empsalarypay item = arr$[i$];
			String key = (new StringBuilder()).append(
					item.getEspEmpno().getId()).append(item.getEspYearmonth())
					.toString();
			payMap.put(key, item.getAcctItems());
		}

		Map monthEbpsMap = new HashMap();
		String key = null;
		Empbenefitplan currPlan = null;
		Empbenefitplan tempPlan = null;
		for (Iterator i$ = ebpList.iterator(); i$.hasNext();) {
			Empbenefitplan plan = (Empbenefitplan) i$.next();
			try {
				tempPlan = (Empbenefitplan) plan.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
			tempPlan.decryEMPPlan(tempPlan);
			List payAcctItems = (List) payMap.get((new StringBuilder()).append(
					tempPlan.getEbpEmpno().getId()).append(
					tempPlan.getEbpYearMonth()).toString());
			if (payAcctItems != null)
				changeEbpToEsav(tempPlan, payAcctItems);
			key = (new StringBuilder()).append(tempPlan.getEbpEmpno().getId())
					.append("").append(tempPlan.getEbpYearMonth()).toString();
			currPlan = (Empbenefitplan) monthEbpsMap.get(key);
			if (currPlan == null) {
				monthEbpsMap.put(key, tempPlan);
				tempPlan.setEmpMonthCount(Integer.valueOf(tempPlan
						.getEmpMonthCount().intValue() + 1));
			} else {
				addToCurrPlan(currPlan, tempPlan);
				currPlan.setEmpMonthCount(Integer.valueOf(currPlan
						.getEmpMonthCount().intValue() + 1));
			}
		}

		return monthEbpsMap;
	}

	public void changeEbpToEsav(Empbenefitplan ebp, List payAcctItems) {
		List ebpAcctItems;
		Empbenefitplan orginalEbp;
		Iterator i$;
		ebpAcctItems = ebp.getAcctItems();
		if (((Empsalaryacctitems) ebpAcctItems.get(0)).getEsaiEsav().getId()
				.equals(
						((Empsalaryacctitems) payAcctItems.get(0))
								.getEsaiEsav().getId()))
			return;
		orginalEbp = null;
		try {
			orginalEbp = (Empbenefitplan) ebp.clone();
		} catch (CloneNotSupportedException e1) {
			e1.printStackTrace();
		}
		i$ = payAcctItems.iterator();
		while (true) {
			Empsalaryacctitems payItem;
			if (!i$.hasNext())
				break;
			payItem = (Empsalaryacctitems) i$.next();
			try {
				PropertyUtils.setProperty(ebp, (new StringBuilder()).append(
						"ebpColumn").append(payItem.getEsaiDataSeq())
						.toString(), null);
			} catch (IllegalAccessException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (InvocationTargetException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (NoSuchMethodException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (payItem.getEsaiEsdd().getEsddDataType().intValue() < 10
					|| payItem.getEsaiEsdd().getEsddDataType().intValue() > 16)
				continue;
			try {
				String newEsddId = payItem.getEsaiEsdd().getEsddId();
				Iterator it = ebpAcctItems.iterator();
				Empsalaryacctitems ebpItem = null;
				do {
					if (!it.hasNext())
						continue;
					ebpItem = (Empsalaryacctitems) it.next();
				} while (!ebpItem.getEsaiEsdd().getEsddId().equals(newEsddId));
				int oriIndex = ebpItem.getEsaiDataSeq().intValue();
				int newIndex = payItem.getEsaiDataSeq().intValue();
				Object oriEbpValue = PropertyUtils.getProperty(orginalEbp,
						(new StringBuilder()).append("ebpColumn").append(
								oriIndex).toString());
				if (oriEbpValue != null)
					PropertyUtils.setProperty(ebp, (new StringBuilder())
							.append("ebpColumn").append(newIndex).toString(),
							((BigDecimal) oriEbpValue).setScale(2));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public Map getSumEbpsOfAllMonth(List payList) {
		String empId = ((Empsalarypay) payList.get(0)).getEspEmpno().getId();
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.createAlias(Empbenefitplan.PROP_EBP_EMP_NO,
				"ebpEmpno", 1);
		detachedCriteria.add(Restrictions.eq("ebpEmpno.id", empId));
		List ebpList = empBenefitDao.findByCriteria(detachedCriteria);
		IEmpSalaryAcctitemsBo esaiBo = (IEmpSalaryAcctitemsBo) SpringBeanFactory
				.getBean("empsalaryacctitemsBo");
		esaiBo.setAcctItemsEbp((Empbenefitplan[]) ebpList
				.toArray(new Empbenefitplan[ebpList.size()]));
		Map payMap = new HashMap();
		Empsalarypay item;
		String key;
		for (Iterator i$ = payList.iterator(); i$.hasNext(); payMap.put(key,
				item.getAcctItems())) {
			item = (Empsalarypay) i$.next();
			key = (new StringBuilder()).append(item.getEspEmpno().getId())
					.append(item.getEspYearmonth()).toString();
		}

		Map monthEbpsMap = new HashMap();
		key = null;
		Empbenefitplan currPlan = null;
		Empbenefitplan tempPlan = null;
		for (Iterator i$ = ebpList.iterator(); i$.hasNext();) {
			Empbenefitplan plan = (Empbenefitplan) i$.next();
			try {
				tempPlan = (Empbenefitplan) plan.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
			tempPlan.decryEMPPlan(tempPlan);
			List payAcctItems = (List) payMap.get((new StringBuilder()).append(
					tempPlan.getEbpEmpno().getId()).append(
					tempPlan.getEbpYearMonth()).toString());
			if (payAcctItems != null)
				changeEbpToEsav(tempPlan, payAcctItems);
			key = (new StringBuilder()).append(tempPlan.getEbpEmpno().getId())
					.append("").append(tempPlan.getEbpYearMonth()).toString();
			currPlan = (Empbenefitplan) monthEbpsMap.get(key);
			if (currPlan == null) {
				monthEbpsMap.put(key, tempPlan);
				tempPlan.setEmpMonthCount(Integer.valueOf(tempPlan
						.getEmpMonthCount().intValue() + 1));
			} else {
				addToCurrPlan(currPlan, tempPlan);
				currPlan.setEmpMonthCount(Integer.valueOf(currPlan
						.getEmpMonthCount().intValue() + 1));
			}
		}

		return monthEbpsMap;
	}

	public List sumEbpList(List ebpList, String searchType) {
		if (ebpList == null || ebpList.size() == 0)
			return null;
		Map sumEbpsMap = new HashMap();
		String key = null;
		Empbenefitplan currPlan = null;
		Empbenefitplan tempPlan = null;
		Integer status = null;
		for (Iterator i$ = ebpList.iterator(); i$.hasNext();) {
			Empbenefitplan plan = (Empbenefitplan) i$.next();
			tempPlan = plan;
			if ("yearMonth".equals(searchType)) {
				key = (new StringBuilder()).append(
						tempPlan.getEbpEmpno().getId()).append(
						tempPlan.getEbpYearMonth()).toString();
				tempPlan.setEbpBelongYearmonth(null);
				status = new Integer(2);
			}
			if ("belongYearMonth".equals(searchType)) {
				key = (new StringBuilder()).append(
						tempPlan.getEbpEmpno().getId()).append(
						tempPlan.getEbpBelongYearmonth()).toString();
				tempPlan.setEbpYearMonth(null);
				status = new Integer(3);
			}
			currPlan = (Empbenefitplan) sumEbpsMap.get(key);
			if (currPlan == null) {
				sumEbpsMap.put(key, tempPlan);
				tempPlan.setEbpStatus(status);
			} else {
				addToCurrPlan(currPlan, tempPlan);
				currPlan.setEbpStatus(status);
			}
		}

		List result = new ArrayList();
		result.addAll(sumEbpsMap.values());
		return result;
	}

	private void addToCurrPlan(Empbenefitplan currPlan, Empbenefitplan plan) {
		Class planClass = currPlan.getClass();
		Method plangetMethod = null;
		Method plansetMethod = null;
		BigDecimal planBD1 = null;
		BigDecimal planBD2 = null;
		try {
			for (int i = 1; i <= 48; i++) {
				plansetMethod = planClass.getMethod((new StringBuilder())
						.append("setEbpColumn").append(i).toString(),
						new Class[] { BigDecimal.class });
				plangetMethod = planClass.getMethod((new StringBuilder())
						.append("getEbpColumn").append(i).toString(),
						new Class[0]);
				planBD1 = (BigDecimal) plangetMethod.invoke(currPlan,
						new Object[0]);
				planBD2 = (BigDecimal) plangetMethod
						.invoke(plan, new Object[0]);
				if (planBD2 != null)
					if (planBD1 == null)
						plansetMethod
								.invoke(currPlan, new Object[] { planBD2 });
					else
						plansetMethod.invoke(currPlan, new Object[] { planBD1
								.add(planBD2) });
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean addCurrPlan(String empId, Empsalarypay pay) {
		Empbenefitplan addPlanSum = pay.getAddBenefitPlan();
		Empbenefitplan plan = new Empbenefitplan();
		Integer plans = pay.getEspBenefitPlans();
		plan.setEbpEsavId(pay.getEspEsavId());
		plan.setAcctItems(pay.getAcctItems());
		plan.setEbpEmpno(pay.getEspEmpno());
		plan.setEbpYearMonth(pay.getEspYearmonth());
		plan.setEbpBelongYearmonth(pay.getEspYearmonth());
		plan.setEbpStatus(new Integer(0));
		plan.setEbpCreateBy(empId);
		plan.setEbpCreateTime(new Date());
		plan.setEbpLastChangeBy(empId);
		plan.setEbpLastChangeTime(plan.getEbpCreateTime());
		Empbenefit benefit = pay.getBenefit();
		if (benefit != null) {
			plan.setEbpHousingAmountb(benefit.getEbfHousingAmount());
			plan.setEbpInsuranceAmountb(benefit.getEbfInsuranceAmount());
			plan.setEbpPensionAmountb(benefit.getEbfPensionAmount());
			plan.setEbpBelongYearmonth(benefit.getBelongYearMonth());
		}
		boolean hasBenefit = false;
		Iterator i$ = pay.getAcctItems().iterator();
		do {
			if (!i$.hasNext())
				break;
			Empsalaryacctitems item = (Empsalaryacctitems) i$.next();
			if (item.getEsaiEsdd().getEsddDataType().intValue() >= 10
					&& item.getEsaiEsdd().getEsddDataType().intValue() <= 16)
				try {
					BigDecimal benefitItemBD = new BigDecimal("0.00");
					Object value = PropertyUtils.getProperty(pay,
							(new StringBuilder()).append("espColumn").append(
									item.getEsaiDataSeq()).toString());
					if (value != null)
						benefitItemBD = (BigDecimal) value;
					if (addPlanSum != null) {
						Object valueAdd = PropertyUtils.getProperty(addPlanSum,
								(new StringBuilder()).append("ebpColumn")
										.append(item.getEsaiDataSeq())
										.toString());
						if (valueAdd != null)
							benefitItemBD = benefitItemBD
									.subtract((BigDecimal) valueAdd);
					}
					PropertyUtils.setProperty(plan, (new StringBuilder())
							.append("ebpColumn").append(item.getEsaiDataSeq())
							.toString(), benefitItemBD);
					hasBenefit = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
		} while (true);
		if (hasBenefit) {
			pay.setBenefitPlan(plan);
			if (plans == null)
				pay.setEspBenefitPlans(Integer.valueOf(1));
			else
				pay.setEspBenefitPlans(Integer.valueOf(plans.intValue() + 1));
			return true;
		} else {
			pay.setBenefitPlan(null);
			pay.setEspBenefitPlans(Integer.valueOf(0));
			return false;
		}
	}

	public boolean deleteEbpById(String ebpId[]) {
		String hql = "delete from Empbenefitplan where id in (";
		for (int i = 0; i < ebpId.length; i++) {
			hql = (new StringBuilder()).append(hql).append("'")
					.append(ebpId[i]).append("'").toString();
			if (i != ebpId.length - 1)
				hql = (new StringBuilder()).append(hql).append(",").toString();
		}

		hql = (new StringBuilder()).append(hql).append(")").toString();
		empBenefitDao.exeHql(hql);
		return true;
	}

	public boolean deleteEbpByYm(String yearMonth, Integer status,
			String empIds[]) {
		String hql = "delete from Empbenefitplan where";
		if (empIds != null && empIds.length > 0)
			hql = (new StringBuilder()).append(hql).append(" ebpEmpno.id in (")
					.append(StringUtil.splitForIn(empIds)).append(") and ")
					.toString();
		if (status == null)
			hql = (new StringBuilder()).append(hql).append(" ebpYearMonth='")
					.append(yearMonth).append("'").toString();
		else if (status.intValue() == 0 || status.intValue() == 1)
			hql = (new StringBuilder()).append(hql).append(" ebpYearMonth='")
					.append(yearMonth).append("' and ebpStatus=")
					.append(status).toString();
		else
			return false;
		empBenefitDao.exeHql(hql);
		return true;
	}

	public Integer getBeneAddCount(String yearMonth) {
		List result = new ArrayList();
		String hql = (new StringBuilder()).append(
				"select count(*) from Empbenefitplan where ebpYearMonth='")
				.append(yearMonth).append("' and ebpStatus=1").toString();
		result = empBenefitDao.exeHqlList(hql);
		return Integer.valueOf(Integer.parseInt(result.get(0).toString()));
	}

	public List getAllYears() {
		String hql = "select distinct substring(ebpYearMonth,1,4) from Empbenefitplan";
		List years = empBenefitDao.exeHqlList(hql);
		if (years.size() == 0)
			return new ArrayList();
		else
			return years;
	}

	public List getEbpList(String yearMonth, String empId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.add(Restrictions.eq("ebpYearMonth", yearMonth));
		detachedCriteria.add(Restrictions.eq("ebpEmpno.id", empId));
		detachedCriteria.addOrder(Order.desc("ebpBelongYearmonth"));
		List ebpList = empBenefitDao.findByCriteria(detachedCriteria);
		return ebpList;
	}

	public boolean updateEbp(Empbenefitplan ebp) {
		empBenefitDao.updateObject(ebp);
		return true;
	}

	public int hasBenefitPlanByAcctVersion(String versionId) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Empbenefitplan.class);
		detachedCriteria.add(Restrictions.eq("ebpEsavId.id", versionId));
		detachedCriteria.setProjection(Projections.rowCount());
		List list = empBenefitDao.findByCriteria(detachedCriteria);
		return ((Integer) list.get(0)).intValue();
	}

	public IEmpBenefitDao getEmpBenefitDao() {
		return empBenefitDao;
	}

	public void setEmpBenefitDao(IEmpBenefitDao empBenefitDao) {
		this.empBenefitDao = empBenefitDao;
	}

	private static final Logger logger = Logger
			.getLogger(EmpBenefitBoImpl.class);
	private IEmpBenefitDao empBenefitDao;

}
